<template>
	<view class="container">
		<!-- 轮播图 -->
		<view class="swiper">
			<u-swiper :list="swiperList" indicator indicatorMode="dot" circular height="200"></u-swiper>
		</view>
		<!-- 选项卡 -->
		<u-sticky style="top: 0;" bgColor="#fff">
			<u-tabs :scrollable="false" lineWidth="60" :list="tabsList" @click="tabsMethods"></u-tabs>
		</u-sticky>
		<!-- 内容区域 -->
		<view class="content">
			<Content @isPhoneChange="isPhoneChange" :tabIndex="tabIndex"></Content>
		</view>
		<u-modal :show="isPhone" title="请先绑定用户信息" showCancelButton @cancel="cancel" @confirm="confirm">
			<template v-slot="content">
				<u--form labelPosition="left" :model="params" :rules="rules" ref="uForm">
					<u-form-item prop="company" borderBottom ref="uForm">
						<!-- <u--input v-model="params.company" placeholder="公司名称" border="none"></u--input>
						<u-picker :show="show" :columns="columns"></u-picker> -->
						<uni-data-select placeholder="请选择公司名称" v-model="params.company" :localdata="CompanyDropDownBox"
							@change="data_select"></uni-data-select>
					</u-form-item>
					<u-form-item prop="userName" borderBottom ref="uForm">
						<u--input v-model="params.userName" placeholder="用户名" border="none" @input="(value)=>params.userName = value.replace(/\s/g,'')"></u--input>
					</u-form-item>
					<u-form-item label="+86" prop="phone" borderBottom ref="uForm">
						<u--input v-model="params.phone" placeholder="手机号码" border="none" maxlength='11' @input="(value)=>params.phone = value.replace(/\s/g,'')"></u--input>
					</u-form-item>
					<u-form-item prop="address" borderBottom ref="uForm">
						<u--input v-model="params.address" placeholder="地址" border="none" @input="(value)=>params.address = value.replace(/\s/g,'')" ></u--input>
					</u-form-item>
				</u--form>
			</template>
		</u-modal>
	</view>
</template>

<script>
	import {
		addPhone,
		login,
		findPhone
	} from '@/api/api.js'
	import {
		findDept
	} from '@/api/applyForInstallation.js'
	import Content from '@/pages/content/index.vue'
	export default {
		components: {
			Content
		},
		data() {
			return {
				CompanyDropDownBox: [],
				params: {
					company: '',
					phone: '',
					userName: '',
					address: '',
					accessToken: null,
				},
				rules: {
					phone: [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur'],
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// uni.$u.test.mobile()就是返回true或者false的
								return uni.$u.test.mobile(value);
							},
							message: '请输入正确的手机号',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}
					],
					userName: [{
						required: true,
						message: '请填写用户名',
						trigger: ['change', 'blur'],
					}, ],
					company: [{
						required: true,
						message: '请选择公司名称',
						trigger: ['change', 'blur'],
					}, ],
					address: [{
						required: true,
						message: '请填写地址',
						trigger: ['change', 'blur'],
					}]
				},
				isPhone: false,
				isWeixin: false,
				userInfo: {},
				tabIndex: 0, // 选项卡index
				swiperList: [
					'/static/homeImg/swiper/1.jpg',
					'/static/homeImg/swiper/2.jpg',
					'/static/homeImg/swiper/3.jpg',
				],
				tabsList: [{
					name: '通知公告',
				}, {
					name: '公司动态',
				}, {
					name: '行业动态',
				}, ]
			}
		},
		// /*
		onLoad() {
			// await this.$onLaunched
			let that = this
			that.drop_down_box()
			// /**
			// 判断token是否存在如果不存在静默登录获取token
			let water = uni.getStorage({
				key: 'accessToken',
				complete(res) {
					if (!res.data.accessToken) {
						// 判断是否是微信内置浏览器
						that.isWeixin = that.isWechat()
						if (that.isWeixin) {
							that.checkWeChatCode() //通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
						}

					} else {
						// *
						//  * 获取当前的最新时间戳与token获取时的时间戳做比较
						//  * 如果newtime>oldtime,说明token失效需要重新获取token

						let newTime = new Date().getTime()
						console.log('最新的时间戳', newTime)
						if (newTime > res.data.tokenTime) {
							console.log('token过期', res.data.tokenTime <= newTime)
							uni.removeStorage({
								key: 'accessToken',
								complete(res) {
									console.log('token过期', res)
									// 判断是否是微信内置浏览器
									that.isWeixin = that.isWechat()
									console.log('that.isWeixin', that.isWeixin)
									if (that.isWeixin) {
										that.checkWeChatCode() //通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
									}
								}
							})
						} else {
							findPhone(res.data.accessToken).then(result => {
								console.log('findPhone', result)
								// 
								//  *如果返回值是空是首次登录
								//  *如果返回值不是空不是首次登录

								if (result.data == '') {
									that.$store.commit("isPhone", true) //首次登录
								} else {
									that.userInfo = result.data
									that.$store.commit("isPhone", false) //首次登录
									uni.setStorage({
										key: 'userInfo',
										data: that.userInfo
									})
									uni.setStorage({
										key: 'isUser',
										data: result.data
									})
								}
								// if (result.data) {
								// 	if (result.data.people_code == null && result.data.people_name ==
								// 		null) {
								// 		that.$store.commit("isPhone", true) //是首次登录
								// 	} else {
								// 		that.userInfo = result.data
								// 		uni.setStorage({
								// 			key: 'userInfo',
								// 			data: that.userInfo
								// 		})
								// 		// that.$store.commit('userInfo',that.userInfo)
								// 		that.$store.commit("isPhone", false) //不是首次登录
								// 	}
								// 	// 存储用户状态
								// 	uni.setStorage({
								// 		key: 'isUser',
								// 		data: result.data
								// 	})
								// } else {
								// 	uni.removeStorage({
								// 		key: 'accessToken',
								// 		complete(res) {
								// 			console.log('token过期', res)
								// 			// 判断是否是微信内置浏览器
								// 			that.isWeixin = that.isWechat()
								// 			console.log('that.isWeixin', that.isWeixin)
								// 			if (that.isWeixin) {
								// 				that.checkWeChatCode() //通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
								// 			}
								// 		}
								// 	})

								// }
							})
						}

					}
				}
			})
		},
		// */
		methods: {
			// inputChange(value){
			// 	this.params.userName = value.replace(/\s/g,'')
			// 	console.log('userName',this.params.userName);
			// },
			async drop_down_box () {
				let CompanyDropDownBox = []
				let selectDictionaries = []
				let result = await findDept()
				console.log('111', result)
				result.data.forEach(item => {
					CompanyDropDownBox.push({
						value: item.dept_name,
						text: item.dept_name
					})
					selectDictionaries.push({
						value: item.dept_id,
						text: item.dept_name
					})
				})
				this.CompanyDropDownBox= CompanyDropDownBox
				this.$store.commit('CompanyDropDownBox', CompanyDropDownBox)
				this.$store.commit('CompanyDropDownBoxDictionaries', selectDictionaries)
				// this.$isResolve()
			},
			data_select(e) {
				console.log('e', e)
			},
			/**
			 * tabsMethods：选项卡点击事件
			 * item:选项卡信息
			 */
			tabsMethods(item) {
				this.tabIndex = item.index
				console.log('tabIndex', this.tabIndex)
			},
			isPhoneChange(item) {
				console.log('homeIsPhone', item)
				this.isPhone = item
			},
			validateField(name, index) {
				console.log('index', index)
				this.current = index
			},
			// 取消
			cancel() {
				this.$refs.uForm.clearValidate()
				this.$refs.uForm.resetFields()
				this.isPhone = false
			},
			// 登录
			confirm() {
				let that = this
				this.$refs.uForm.validate().then(res => {
					uni.getStorage({
						key: 'accessToken',
						complete(res) {
							if (res.data) {
								that.params.accessToken = res.data.accessToken
								console.log('then', that.params)
								/**
								 * 1、首先通过获取最新时间判断token是否过期
								 */
								let newTime = new Date().getTime()
								if (newTime > res.data.tokenTime) {
									uni.removeStorage({
										key: 'accessToken',
										complete(res) {
											console.log('token过期', res)
											// 判断是否是微信内置浏览器
											that.isWeixin = that.isWechat()
											console.log('that.isWeixin',
												that.isWeixin)
											if (that.isWeixin) {
												that.checkWeChatCode() //通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
											}
										}
									})
								} else {
									// 绑定手机号
									addPhone(that.params).then(result => {
										// 如果返回值是空绑定注册失败
										if (result.data == '') {
											that.isPhone = false
											uni.showModal({
												title: '绑定失败！'
											})
										} else {
											uni.setStorage({
												key: 'userInfo',
												data: result.data
											})
											that.$store.commit("isPhone", false)
											that.isPhone = false
											uni.showModal({
												title: '绑定成功！'
											})
										}
									})
								}
							}
						}
					})

				}).catch(res => {
					console.log('catch', this.params)
				})
			},
			//方法：用来判断是否是微信内置的浏览器
			isWechat() {
				console.log('微信浏览器判断')
				return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
			},
			//方法:用来提取code
			getUrlCode(name) {
				console.log('提取code')
				return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(
						location.href) || [, ''])[1]
					.replace(/\+/g, '%20')) || null
			},
			//检查浏览器地址栏中微信接口返回的code
			checkWeChatCode() {
				console.log('监测微信浏览器是否有CODE')
				let code = this.getUrlCode('code')
				if (code) {
					console.log('true', code)
					this.getOpenidAndUserinfo(code)
				} else {
					console.log('false', code)
					this.getWeChatCode()
				}
			},
			//请求微信接口，用来获取code
			getWeChatCode() {
				let local = encodeURIComponent('https://lxsw.pcippc.com/'); //获取当前页面地址作为回调地址
				// let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址
				// let appid = 'wx873a10f022021245'//PCIPPC
				let appid = 'wxeee1e01af3c0812b' //岚县经开区供水中心
				//通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
				// 非静默
				// window.location.href =
				// 	`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${local}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect;`
				// 静默
				window.location.href =
					`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${local}&response_type=code&scope=snsapi_base&state=1#wechat_redirect;`

			},
			// 如果有code自己登录
			async getOpenidAndUserinfo(code) {
				let that = this
				let result = await login(code)
				console.log('登录接口', result)
				let isPhone = await findPhone(result.data.access_token)
				console.log('isPhone', isPhone)
				let tokenTime = new Date().getTime() + 7200000
				console.log('过期时间', tokenTime)
				uni.setStorage({
					key: 'accessToken',
					data: {
						accessToken: result.data.access_token,
						tokenTime: tokenTime
					},
				})
				/**
				 * 如果isPhone.data返回值不为空的话不是首次登录
				 * 如果isPhone.data返回值为空的话是首次登录
				 */
				if (isPhone.data !== '') {
					that.userInfo = isPhone.data
					uni.setStorage({
						key: 'userInfo',
						data: that.userInfo
					})

					uni.setStorage({
						key: 'isUser',
						data: isPhone.data
					})
					that.$store.commit('isPhone', false)
				} else {
					that.$store.commit('isPhone', true)
				}
				// if (isPhone.data) {
				// 	if (isPhone.data.people_code == null && isPhone.data.people_name == null) {
				// 		this.$store.commit("isPhone", true)
				// 	} else {
				// 		that.userInfo = isPhone.data
				// 		uni.setStorage({
				// 			key: 'userInfo',
				// 			data: that.userInfo
				// 		})
				// 		this.$store.commit("isPhone", false)
				// 	}
				// 	uni.setStorage({
				// 		key: 'isUser',
				// 		data: isPhone.data
				// 	})
				// 	// if (isPhone.data.user_role == '1') {
				// 	// 	this.$store.commit("isUser", isPhone.data)
				// 	// } else {
				// 	// 	this.$store.commit("isUser", isPhone.data)
				// 	// }
				// } else {
				// 	uni.removeStorage({
				// 		key: 'accessToken',
				// 		complete(res) {
				// 			console.log('token过期', res)
				// 			// 判断是否是微信内置浏览器
				// 			that.isWeixin = that.isWechat()
				// 			console.log('that.isWeixin', that.isWeixin)
				// 			if (that.isWeixin) {
				// 				that.checkWeChatCode() //通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
				// 			}
				// 		}
				// 	})
				// }

			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		width: 100%;
		min-height: 100vh;
		background: #f4f4f5;
		display: inline-block;

		// 内容
		.content {
			width: 100%;
		}

		/deep/.uni-select__selector {
			height: 100px;

			.uni-select__selector-scroll {
				height: 100%;
			}
		}
	}
</style>